package controller

import com.alibaba.fastjson.JSONObject
import com.huawei.services.runtime.Context
import com.huawei.services.runtime.entity.apig.APIGTriggerEvent
import com.huawei.services.runtime.entity.apig.APIGTriggerResponse
import controller.vo.ActivityInfoVo
import controller.vo.JsonBody
import controller.vo.UserVo
import entity.Activity
import entity.ActivityType
import entity.User
import repository.Page
import repository.Pageable
import repository.Sort
import service.activity.ActivityInfo
import service.activity.ActivityService
import service.activity.ActivityServiceImpl
import service.activity.generateActivityInfo
import service.activity.signup.SignUpActivityService
import service.activity.signup.SignUpActivityServiceImpl
import service.user.UserService
import service.user.UserServiceImpl
import java.util.HashMap


class ActivityController {
    private val activityService: ActivityService = ActivityServiceImpl()

    private val signUpActivityService: SignUpActivityService = SignUpActivityServiceImpl()

    private val userService: UserService = UserServiceImpl()

//    private val pictureService: PictureService = PictureServiceImpl()


    //根据id获取活动信息
    // Get /activities/{id}
    fun getActivity(event: APIGTriggerEvent?, context: Context?): APIGTriggerResponse? {
        val headers: MutableMap<String, String> = HashMap()
        headers["Content-Type"] = "application/json"
        var activity: Activity? = null
        var aId = -1
        event?.let {
            val prePath = "activities/"
            aId = getIdFromPath(it.path, prePath)
            activity = activityService.findActivity(aId)
        }
        activity?.let {
            return APIGTriggerResponse(200, headers, JSONObject.toJSONString(JsonBody(0, "成功",
                    ActivityInfoVo(it, signUpActivityService.getUserForm(aId, true).size))))
        } ?: return APIGTriggerResponse(403, headers, JSONObject.toJSONString(JsonBody(-1, "没有该活动id=$aId",
                Any())))
    }
//    @GetMapping("/activities/{id}")

    //    fun getActivity(@PathVariable("id") id: Int): ResponseEntity<*> {
//        var a = activityService.findActivity(id)
//                ?: return ResponseEntity.badRequest().body(JsonBody(-1, "没有该活动id=$id", Any()))
//        var aIf = ActivityInfoVo(a, signUpActivityService.getUserForm(id, true).size)
//        return ResponseEntity.ok(JsonBody(0, "成功", aIf))
//    }
//
//    //查看某活动所有参与者
    //Get /activities/{id}/joiners?page={page}&size={size}
    fun getJoiners(event: APIGTriggerEvent?, context: Context?): APIGTriggerResponse? {
        val headers: MutableMap<String, String> = HashMap()
        headers["Content-Type"] = "application/json"
        val parameters = event?.queryStringParameters
        var aId = -1
        event?.let {
            val prePath = "activities/"
            aId = getIdFromPath(it.path, prePath)
        }
        if (aId > 0) {
            parameters?.let {
                val page = Integer.parseInt(it["page"])
                val size = Integer.parseInt(it["size"])
                val result = signUpActivityService.getUserForm(aId, true, Pageable(page, size))
                return APIGTriggerResponse(200, headers, JSONObject.toJSONString(JsonBody(0, "成功",
                        result.content.map {
                            UserVo().apply {
                                setInfo(it)
                            }
                        })))

            }
            return APIGTriggerResponse(403, headers, JSONObject.toJSONString(JsonBody(-1, "路径参数未填写",
                    Any())))
        }
        return APIGTriggerResponse(403, headers, JSONObject.toJSONString(JsonBody(-1, "没有该活动id=$aId",
                Any())))
    }

    //    @GetMapping("/activities/{id}/joiners")
//    fun getJoiners(@PathVariable("id") id: Int, @RequestParam page: Int, @RequestParam size: Int): ResponseEntity<*> {
//        val pageable = PageRequest.of(page, size)
//        var result = signUpActivityService.getUserForm(id, true, pageable)
//        return ResponseEntity.ok(JsonBody(0, "成功", result.content.map {
//            UserVo().apply {
//                setInfo(it)
//            }
//        }))
//    }
//
//    //为某活动添加一条参加申请
    // Post /activities/{activityId}/joiners/{userId}
    fun addApply(event: APIGTriggerEvent?, context: Context?): APIGTriggerResponse? {
        val headers: MutableMap<String, String> = HashMap()
        headers["Content-Type"] = "application/json"
        var aId = -1
        var uId = -1
        event?.let {
            var prePath = "activities/"
            aId = getIdFromPath(it.path, prePath)
            prePath = "joiners/"
            uId = getIdFromPath(it.path, prePath)
        }
        if (aId == -1 || uId == -1) {
            return APIGTriggerResponse(403, headers, JSONObject.toJSONString(JsonBody(-1, "没有该活动或用户",
                    Any())))
        }
        signUpActivityService.signUp(uId, aId)
        return APIGTriggerResponse(200, headers, JSONObject.toJSONString(JsonBody(0, "成功",
                Any())))
    }

    //    @PostMapping("/activities/{activityId}/joiners/{userId}")
//    fun addApply(@PathVariable("activityId") aId: Int, @PathVariable("userId") uId: Int): ResponseEntity<*> {
//        signUpActivityService.signUp(uId, aId)
//        return ResponseEntity.ok(JsonBody(0, "成功", Any()))
//    }
//
//    //提供主页活动推荐
    // Get /activities/home?order={order}&page={page}&size={size}
    fun getActivitiesByOrder(event: APIGTriggerEvent?, context: Context?): APIGTriggerResponse? {
        val headers: MutableMap<String, String> = HashMap()
        headers["Content-Type"] = "application/json"
        val parameters = event?.queryStringParameters
        parameters?.let { it ->
            val page = Integer.parseInt(it["page"])
            val size = Integer.parseInt(it["size"])
            val result = when (it["order"]) {
                "hotest" -> {
                    //按活动开始时间升序排列
                    val pageable = Pageable(page, size, Sort.Direction.ASC, "startTime")
                    activityService.findActivity(true, pageable)
                }
                "latest" -> {
                    //按活动开始时间升序排列
                    val pageable = Pageable(page, size, Sort.Direction.ASC, "startTime")
                    activityService.findActivity(true, pageable)
                }
                else -> {
                    val pageable = Pageable(page, size)
                    activityService.findActivity(true, pageable)
                }
            }

            return APIGTriggerResponse(200, headers, JSONObject.toJSONString(JsonBody(0, "成功",
                    Page(result.content.map { a ->
                        ActivityInfoVo(a, signUpActivityService.getUserForm(a.id, true).size)
                    },result.pageable,result.totalElements))))
        } ?: return APIGTriggerResponse(403, headers, JSONObject.toJSONString(JsonBody(-1, "路径参数未填写",
                Any())))

    }

    //    @GetMapping("/activities/home")
//    fun getActivitiesByOrder(@RequestParam order: String, @RequestParam page: Int, @RequestParam size: Int): ResponseEntity<*> {
//        val page = when (order) {
////            "default" -> {
////
////            }
//            "hotest" -> {
//                //按活动开始时间升序排列
//                val pageable = PageRequest.of(page, size, Sort.Direction.ASC, "startTime")
//                activityService.findActivity(true, pageable)
//
//            }
//            "latest" -> {
//                //按活动开始时间升序排列
//                val pageable = PageRequest.of(page, size, Sort.Direction.ASC, "startTime")
//                activityService.findActivity(true, pageable)
//            }
//            else -> {
//                val pageable = PageRequest.of(page, size)
//                activityService.findActivity(true, pageable)
//            }
//        }
//
//        return ResponseEntity.ok(JsonBody(0, "成功", page.content.map {
//            it?.let {
//                ActivityInfoVo(it, signUpActivityService.getUserForm(it.id, true).size)
//            }
//        }))
//    }
//
//    //根据名字检索活动
    // Get /activities?name={string}
    fun getActivitiesByName(event: APIGTriggerEvent?, context: Context?): APIGTriggerResponse? {
        val headers: MutableMap<String, String> = HashMap()
        headers["Content-Type"] = "application/json"
        val parameters = event?.queryStringParameters
        parameters?.let { it ->
            val name = it["name"]
                    ?: return APIGTriggerResponse(403, headers, JSONObject.toJSONString(JsonBody(-1, "路径参数不规范",
                            Any())))
            return APIGTriggerResponse(200, headers, JSONObject.toJSONString(JsonBody(0, "成功",
                    activityService.findActivity(name).map { a ->
                        ActivityInfoVo(a, signUpActivityService.getUserForm(a.id, true).size)
                    })))
        } ?: return APIGTriggerResponse(403, headers, JSONObject.toJSONString(JsonBody(-1, "路径参数未填写",
                Any())))
    }

    //    @GetMapping("/activities")
//    fun getActivitiesByName(@RequestParam name: String/*, @RequestParam kind: ActivityType*/): ResponseEntity<*> {
//        return ResponseEntity.ok(JsonBody(0, "成功", activityService.findActivity(name).map {
//            ActivityInfoVo(it, signUpActivityService.getUserForm(it.id, true).size)
//        }))
//
//    }
//
//    //添加活动
    // Post /activities
    // Request Body
    //{
    //    "activityName": "活动名称",
    //    "activityProfile": "活动简介",
    //    "activityStart": 123, // 时间戳
    //    "activityEnd": 321, // 时间戳
    //    "activityKind": "STUDY", //枚举类型：STUDY,PLAY,SPORTS,READING,OTHERS
    //    "activityLocation": "活动地点",
    //    "activityPic": "活动图片",
    //    "publisherId": 4 // Int
    //}
    fun addNewActivity(event: APIGTriggerEvent?, context: Context?): APIGTriggerResponse? {
        val headers: MutableMap<String, String> = HashMap()
        headers["Content-Type"] = "application/json"
        val info = JSONObject.parseObject(event?.rawBody)
        val activityInfo = generateActivityInfo(info)
        val publisher = userService.getUser(info.getIntValue("publisherId"))
        val examiner = userService.pickOneExaminer()
        publisher?.let {

            val id = activityService.publishActivity(activityInfo, it, examiner)
            return APIGTriggerResponse(200, headers, JSONObject.toJSONString(JsonBody(0, "成功",
                    id)))
        } ?: return APIGTriggerResponse(403, headers, JSONObject.toJSONString(JsonBody(-1, "未找到发布者",
                Any())))
    }

    //    @PostMapping("/activities")
//    fun addNewActivity(@RequestBody info: ActivityInfoVo): ResponseEntity<JsonBody<*>> {
//        val activityInfo = generateActivityInfo(info)
//        val publisher = userService.getUser(info.publisherId)
//        val examiner = userService.pickOneExaminer()
//        publisher?.let {
//
//            val id = activityService.publishActivity(activityInfo, it, examiner)
//            return ResponseEntity.ok(JsonBody(0, "成功", id))
//
//        } ?: return ResponseEntity.badRequest().body(JsonBody(-1, "未找到发布者", Any()))
//    }
//
//    //修改活动信息
//     Put /activities/{id}
    // Request Body
    //{
    //    "activityName": "活动名称",
    //    "activityProfile": "活动简介",
    //    "activityStart": 123, // 时间戳
    //    "activityEnd": 321, // 时间戳
    //    "activityKind": "STUDY", //枚举类型：STUDY,PLAY,SPORTS,READING,OTHERS
    //    "activityLocation": "活动地点",
    //    "activityPic": "活动图片",
    //    "publisherId": 4 // Int
    //}
    fun changeActivityInfo(event: APIGTriggerEvent?, context: Context?): APIGTriggerResponse? {
        val headers: MutableMap<String, String> = HashMap()
        headers["Content-Type"] = "application/json"
        val info = JSONObject.parseObject(event?.rawBody)
        val activityInfo = generateActivityInfo(info)
        event?.let {
            val aId = getIdFromPath(it.path, "activities/")
            activityService.changeActivityInfo(aId, activityInfo)
            return APIGTriggerResponse(200, headers, JSONObject.toJSONString(JsonBody(0, "成功",
                    Any())))
        }
        return APIGTriggerResponse(403, headers, JSONObject.toJSONString(JsonBody(-1, "请求不合规",
                Any())))
    }


    //    @PutMapping("/activities/{id}")
//    fun changeActivityInfo(@PathVariable("id") aId: Int, @RequestBody info: ActivityInfoVo): ResponseEntity<*> {
//        val activityInfo = generateActivityInfo(info)
//        activityService.changeActivityInfo(aId, activityInfo)
//        return ResponseEntity.ok(JsonBody(0, "成功", Any()))
//    }
//
//    //上传活动图片
//     POST /activities/{id}/banner

//     form data
//     file=[fileData1,fileData2]

    fun uploadBanner(event: APIGTriggerEvent?, context: Context?): APIGTriggerResponse? {
        val headers: MutableMap<String, String> = HashMap()
        headers["Content-Type"] = "application/json"
        return APIGTriggerResponse(500, HashMap(), JSONObject.toJSONString(JsonBody(-1, "暂不支持",
                Any())))
        //TODO()
    }

    //    @PostMapping("/activities/{id}/banner")
//    fun uploadBanner(@PathVariable("id") aId: Int, @RequestParam("file", required = false) file: MultipartFile?): ResponseEntity<*> {
//        file?.let {
//            return ResponseEntity.ok(JsonBody(0, "成功", pictureService.saveBanner(it, aId)))
//
//        }
//        return ResponseEntity.badRequest().body(JsonBody(-1, "失败", Any()))
//    }
//
//    //获取某活动签到的参与者
//     GET /activities/{id}/sign?state={state}
    fun getSignJoiners(event: APIGTriggerEvent?, context: Context?): APIGTriggerResponse? {
        val headers: MutableMap<String, String> = HashMap()
        headers["Content-Type"] = "application/json"
        event?.let {
            val aId = getIdFromPath(it.path, "activities/")
            val state = it.queryStringParameters["state"] == "true"
            val result = signUpActivityService.getSignJoiners(aId, state).map {
                UserVo().apply { setInfo(it) }
            }
            return APIGTriggerResponse(200, headers, JSONObject.toJSONString(JsonBody(0, "成功",
                    result)))
        }
        return APIGTriggerResponse(403, headers, JSONObject.toJSONString(JsonBody(-1, "请求不合规",
                Any())))
    }

    //    @GetMapping("/activities/{id}/sign")
//    fun getSignJoiners(@PathVariable("id") aId: Int, @RequestParam("state") state: Boolean): ResponseEntity<*> {
//        val result = signUpActivityService.getSignJoiners(aId, state).map {
//            UserVo().apply { setInfo(it) }
//        }
//        return ResponseEntity.ok(JsonBody(0, "成功", result))
//    }
//
//    //获取活动图片
//     Get /{bannerUrl}
    fun getBanner(event: APIGTriggerEvent?, context: Context?): APIGTriggerResponse? {
        val headers: MutableMap<String, String> = HashMap()
        headers["Content-Type"] = "application/json"
        return APIGTriggerResponse(500, HashMap(), JSONObject.toJSONString(JsonBody(-1, "暂不支持",
                Any())))
        //TODO()
    }

//    @GetMapping("/banner/{picName}", produces = [MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_PNG_VALUE])
//    fun getBanner(response: HttpServletResponse, @PathVariable("picName") picName: String) {
//        pictureService.responseBanner(response, picName)
//
//    }

}